#include<iostream>
#include"Date.h"

using namespace std;

Date::Date(int y, int m, int d):year(y), month(m), day(d)
{
	if (!isDateRight())
	{
		year = 2023;
		month = 1;
		day = 1;
	}
}

Date::Date(const Date& date)
{
	year = date.year;
	month = date.month;
	day = date.day;
}

Date::Date(const Date &bd, int borrowTime)
{
	if (borrowTime >= 0)
	{
		//先拷贝bd(borrowDate)的数据成员，再进行运算
		int* year0 = new int(bd.year);
		int* month0 = new int(bd.month);
		int* day0 = new int(bd.day);

		int m2;//记录2月天数

		year = bd.year;
		if (isLeepYear())
		{
			m2 = 29;
		}
		else
		{
			m2 = 28;
		}

		int m_days[] = { 0,31,m2,31,30,31,30,31,31,30,31,30,31 };//记录每月天数

		int days = *day0 + borrowTime;
		int m_day = 0;

		//通过循环得出归还日期并赋该新值
		while (days > 0)
		{
			if (days - m_days[*month0] > 0)
			{
				days -= m_days[*month0];
				(*month0)++;
			}
			else
			{
				m_day = days;
				days = 0;
			}

			if (*month0 > 12)
			{
				*month0 = 1;
				(*year0)++;
			}
		}

		year = *year0;
		month = *month0;
		day = m_day;

		delete year0, month0, day0;
	}

	else
	{
		year = bd.year;
		month = bd.month;
		day = bd.day;
	}
}

void Date::showDate() const
{
	cout << year << "/" << month << "/" << day;
}

void Date::setDate(int y, int m, int d)
{
	int* year0 = new int(year);
	int* month0 = new int(month);
	int* day0 = new int(day);

	year = y;
	month = m;
	day = d;

	if (!isDateRight())
	{
		year = *year0;
		month = *month0;
		day = *day0;
	}

	delete year0, month0, day0;
}

int Date::getYear() const
{
	return year; 
}

int Date::getMonth() const
{
	return month; 
}

int Date::getDay() const
{
	return day; 
}

bool Date::isLeepYear() const
{
	if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
	{
		return true;
	}

	return false;
}

bool Date::isDateRight() const
{
	if (day > 0 && month > 0 && day <= 31 && month <= 12)
	{
		if ((month <= 7 && month % 2 != 0) || (month>=8 && month % 2 == 0))
		{
			if (day <= 31)
			{
				return true;
			}

			return false;
		}

		if (month == 2)
		{
			if (isLeepYear())
			{
				if (day <= 29)
				{
					return true;
				}

				return false;
			}
			else
			{
				if (day <= 28)
				{
					return true;
				}

				return false;
			}
		}

		else
		{
			if (day <= 30)
			{
				return true;
			}

			return false;
		}
	}

	return false;
}
